package edu.sctu.java.advanced.pattern.valve;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class StandardPipeline implements Pipeline {
    Valve first;
    Valve basic;

    @Override
    public void setBasic(Valve v) {
        this.basic = v;
        if (this.first != null) {
            Valve current = this.first;
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(v);

        }
        this.basic = v;
    }

    @Override
    public Valve getBasic() {
        return this.basic;
    }

    @Override
    public Valve getFirst() {
        if (this.first != null)
            return this.first;
        else
            return this.basic;
    }

    @Override
    public Valve[] getValves() {
        List<Valve> valveList = new ArrayList<Valve>();

        Valve current = this.first;
        if (current == null) {
            current = this.basic;
        }

        while (current != null) {
            valveList.add(current);
            current = current.getNext();
        }
        return valveList.toArray(new Valve[0]);
    }

    @Override
    public void addValve(Valve v) {

        if (this.first == null) {
            this.first = v;
            this.first.setNext(this.basic);
        } else {

            Valve current = this.first;

            while (current.getNext() != this.basic) {
                current = current.getNext();
            }

            current.setNext(v);
            v.setNext(this.basic);

        }
    }

    @Override
    public void start() {
        Context context = new Context("chen");
        Valve current = this.first;

        while (current != null) {
            current.invoke(context);

            current = current.getNext();
        }

        System.out.println(context.name);
    }
}
